package cn.zmit.kuxi.activity;

import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.Random;
import java.util.Timer;
import java.util.TimerTask;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import org.json.JSONException;
import org.json.JSONObject;

import android.annotation.SuppressLint;
import android.app.Dialog;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.Editable;
import android.text.InputType;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.inputmethod.EditorInfo;
import android.view.inputmethod.InputMethodManager;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ProgressBar;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;
import cn.zmit.kuxi.R;
import cn.zmit.kuxi.activity.binner.SliderBanner;
import cn.zmit.kuxi.adapter.MainSliderBannerOne;
import cn.zmit.kuxi.alipay.PayResult;
import cn.zmit.kuxi.alipay.SignUtils;
import cn.zmit.kuxi.contants.SPConstants;
import cn.zmit.kuxi.request.RequestTask;
import cn.zmit.kuxi.widget.PtrHeader;

import com.alipay.sdk.app.PayTask;
import com.lidroid.xutils.ViewUtils;
import com.lidroid.xutils.view.annotation.ViewInject;
import com.lidroid.xutils.view.annotation.event.OnClick;
import com.xdroid.common.utils.PreferenceHelper;
import com.xdroid.common.utils.ScreenUtils;
import com.xdroid.common.utils.StringUtils;
import com.xdroid.common.utils.ToastUtils;
import com.xdroid.functions.request.JsonData;
import com.xdroid.request.extension.XDroidRequest;
import com.xdroid.request.extension.config.DataType;
import com.xdroid.request.extension.impl.OnRequestListenerAdapter;
import com.xdroid.widget.ptr.PtrDefaultHandler;
import com.xdroid.widget.ptr.PtrFrameLayout;
import com.xdroid.widget.ptr.PtrHandler;

/** * @author @parameter * @return */
public class NowJoinActivity extends BaseActivity {
	// @ViewInject(R.id.goodsJazzyViewPager)
	// private JazzyViewPager goodsJazzyViewPager;
	// @ViewInject(R.id.tv_current_goods_image_item)
	private TextView tv_current_goods_image_item;
	// @ViewInject(R.id.tv_all_goods_image_count)
	private TextView tv_all_goods_image_count;
	@ViewInject(R.id.tv_goods_title_join)
	private TextView tv_goods_title_join;
	@ViewInject(R.id.tv_goods_detail_data)
	private TextView tv_goods_detail_data;
	@ViewInject(R.id.tv_goods_introduction)
	private TextView tv_goods_introduction;
	@ViewInject(R.id.progressBarPeople)
	private ProgressBar progressBarPeople;
	@ViewInject(R.id.tv_goods_allPeople)
	private TextView tv_goods_allPeople;
	@ViewInject(R.id.tv_goods_alreadyJoin)
	private TextView tv_goods_alreadyJoin;
	@ViewInject(R.id.tv_buy_number)
	private TextView tv_buy_number;

	@ViewInject(R.id.tv_buy_num)
	private TextView tv_buy_num;
	@ViewInject(R.id.tv_winProbability)
	private TextView tv_winProbability;
	@ViewInject(R.id.tv_Prompt)
	private TextView tv_Prompt;
	@ViewInject(R.id.tv_allMoney)
	private TextView tv_allMoney;

	@ViewInject(R.id.img_kubi)
	private ImageView img_kubi;
	@ViewInject(R.id.img_pay)
	private ImageView img_pay;
	@ViewInject(R.id.rl_kubi)
	private RelativeLayout rl_kubi;
	@ViewInject(R.id.rl_ailpay)
	private RelativeLayout rl_pay;

	private String description, title, goodsName, allNeed, joinCount, gp_id,
			flag;
	private double result;
	private String userId;
	private int newdata;

	Dialog dialog;
	int dialogNum = 0;
	int num;
	String newNumber;
	int newnumber;
	EditText cont;
	int residue;
	private SharedPreferences sp;

	// check intalled app
	public Boolean isInstalled(Context context) {
		PackageManager pm = getPackageManager();
		List<PackageInfo> infos = pm.getInstalledPackages(0);
		for (PackageInfo info : infos) {
			if (info.packageName.equals("com.eg.android.AlipayGphone")) {
				return true;
			}
		}
		return false;
	}

	int type = 0;// 支付方式， 0 支付宝；1 酷币 默认 支付宝
	/**
	 * 装ImageView数组
	 */
	private ImageView[] mImageViews;
	private List<String> strings;
	Boolean hasLog;

	@ViewInject(R.id.slider_banner)
	private SliderBanner sliderBanner;
	/**
	 * 轮播图控制器
	 */
	private MainSliderBannerOne mainSliderBanner;

	// 下拉刷新
	@ViewInject(R.id.ptr_view)
	private PtrFrameLayout ptr_view;
	private PtrHeader ptrHeader;
	private int i_gp_id;
	private int i_data;

	@Override
	protected void onRestart() {
		super.onRestart();
		getData();
	}

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
		setTitleView("立即参与", true);
		setContentView(R.layout.activity_now_join);
		ViewUtils.inject(this);
		initView();
		hasLog = PreferenceHelper.readBoolean(context,
				SPConstants.SHARED_PREFERENCE_NAME, SPConstants.HAS_LOGGED,
				false);
		if (hasLog) {
			userId = PreferenceHelper.readString(context,
					SPConstants.SHARED_PREFERENCE_NAME, SPConstants.USERID, "");
		}

		initSliderBanner();
		initPtr();
		initType();
		int zong = Integer.parseInt(allNeed);
		double getWin = ((float) 1 / (float) zong) * 100;
		String win = String.format("%.2f", getWin);// 转化保留两位小数
		tv_buy_number.setText("购买商品数量：" + 1 + "" + "件");
		tv_winProbability.setText("中奖概率：" + win + "%");

		// 监听文本的变化
		tv_buy_num.addTextChangedListener(new TextWatcher() {

			@Override
			public void onTextChanged(CharSequence arg0, int arg1, int arg2,
					int arg3) {
			}

			@Override
			public void beforeTextChanged(CharSequence arg0, int arg1,
					int arg2, int arg3) {
			}

			@Override
			public void afterTextChanged(Editable arg0) {
				// Toast.makeText(NowJoinActivity.this, arg0, 0).show();
				String arg1 = arg0 + "";
				if (!TextUtils.isEmpty(arg1)) { // 为空则转化int会报错
					int arg2 = Integer.parseInt(arg1);
					int zong = Integer.parseInt(allNeed);
					if (arg2 > residue) {
						double getWin = ((float) residue / (float) zong) * 100;
						String win = String.format("%.2f", getWin);// 转化保留两位小数
						tv_buy_number.setText("购买商品数量：" + residue + "" + "件");
						tv_winProbability.setText("中奖概率：" + win + "" + "%");
						tv_allMoney.setText("共参与" + residue + "" + "件商品"
								+ "     " + "总计" + residue + "" + "元");
					} else {
						double getWin = ((float) arg2 / (float) zong) * 100;
						String win = String.format("%.2f", getWin);// 转化保留两位小数
						tv_buy_number.setText("购买商品数量：" + arg2 + "" + "件");
						tv_winProbability.setText("中奖概率：" + win + "" + "%");
						tv_allMoney.setText("共参与" + arg2 + "" + "件商品" + "     "
								+ "总计" + arg2 + "" + "元");
					}

				}
			}
		});
	}

	private void getData() {
		RequestTask.getInstance().getGoodsDetail(this, gp_id,
				new PiconRequestListener());
	};

	private int buy_count;

	private class PiconRequestListener extends OnRequestListenerAdapter<Object> {

		@Override
		public void onDone(XDroidRequest<?> request, String response,
				DataType dataType) {
			// TODO Auto-generated method stub
			super.onDone(request, response, dataType);
			JsonData jsonData = JsonData.create(response);
			JsonData data = jsonData.optJson("info");
			if (data != null && data.length() > 0) {
				String pic = data.optString("pictures");
				buy_count = data.optInt("buy_count");
				// Log.e("count===", buy_count);
				strings = new ArrayList<String>();
				String[] picArray = pic.split("[|]");
				for (int i = 0; i < picArray.length; i++) {
					String picUrl = picArray[i];
					strings.add(picUrl);
				}
				mainSliderBanner.play(data.optJson("banner"), true);
			}
			tv_goods_alreadyJoin.setText("已参与：" + buy_count);
			ptr_view.refreshComplete();
		}

		@Override
		public void onRequestPrepare() {
			// TODO Auto-generated method stub
			super.onRequestPrepare();
		}

		@Override
		public void onRequestFailed(String error) {
			// TODO Auto-generated method stub
			super.onRequestFailed(error);
		}
	}

	@SuppressLint("DefaultLocale")
	@OnClick({ R.id.bt_delet, R.id.bt_add, R.id.tv_buy_num, R.id.btn_nowCommit,
			R.id.rl_ailpay, R.id.rl_kubi })
	private void OnClick(View v) {
		switch (v.getId()) {
		case R.id.rl_ailpay:
			type = 0;
			img_kubi.setVisibility(View.GONE);
			img_pay.setVisibility(View.VISIBLE);
			break;
		case R.id.rl_kubi:
			type = 1;
			img_kubi.setVisibility(View.VISIBLE);
			img_pay.setVisibility(View.GONE);
			break;
		case R.id.bt_delet:// 减
			int zong = Integer.parseInt(allNeed);

			int delet = StringUtils.toInt(tv_buy_num.getText().toString()
					.trim());
			newdata = delet - 1;
			if (newdata == 0) {
				ToastUtils.show(context, "购买商品数量不能小于0");
			} else {
				double getWin = ((float) newdata / (float) zong) * 100;
				String win = String.format("%.2f", getWin);// 转化保留两位小数
				tv_buy_num.setText(newdata + "");
				// tv_buy_num.setSelection((newdata + "").length());
				tv_buy_number.setText("购买商品数量：" + newdata + "" + "件");
				tv_winProbability.setText("中奖概率：" + win + "" + "%");
				tv_allMoney.setText("共参与" + newdata + "" + "件商品" + "     "
						+ "总计" + newdata + "" + "元");
			}

			break;
		case R.id.bt_add:// 加
			int all = Integer.parseInt(allNeed);
			int join = Integer.parseInt(joinCount);
			int typer = all - join;

			String data_add = tv_buy_num.getText().toString().trim();
			int b = Integer.parseInt(data_add);

			newdata = ++b;
			if (newdata <= typer) {
				// float a = all;
				double getWin = ((float) newdata / (float) all) * 100;
				String win = String.format("%.2f", getWin);// 转化保留两位小数

				tv_buy_num.setText(newdata + "");
				// tv_buy_num.setSelection((newdata + "").length());
				tv_buy_number.setText("购买商品数量：" + newdata + "" + "件");
				tv_winProbability.setText("中奖概率：" + win + "" + "%");

				tv_allMoney.setText("共参与" + newdata + "" + "件商品" + "     "
						+ "总计" + newdata + "" + "元");

			} else {
				ToastUtils.show(context, "剩余数量不足");
			}

			break;
		case R.id.btn_nowCommit:// 提交
			if (hasLog) {
				if (type == 0) {// 支付宝支付
					String data = tv_buy_num.getText().toString().trim();
					Map<String, Object> map = new HashMap<String, Object>();
					// JSONArray jsonArray = new JSONArray();
					// JSONObject object = new JSONObject();
					// try {
					// // i_gp_id = Integer.parseInt(gp_id);
					// // i_data = Integer.parseInt(data);
					// object.put("gp_id", gp_id);
					// object.put("number", data);
					// jsonArray.put(object);
					// } catch (JSONException e) {
					// e.printStackTrace();
					// }
					map.put("user_id", userId);
					map.put("gp_id", gp_id);
					map.put("portion", data);
					map.put("type", 1 + "");// 支付宝支付，这里之所以用1|2不用0，1是homer想要我传1|2
					RequestTask.getInstance().doCommitGoods(this, map,
							new onCommitRequestListener());

				}
				if (type == 1) {// 酷币支付
					String data = tv_buy_num.getText().toString().trim();
					Map<String, Object> map = new HashMap<String, Object>();
					// JSONArray jsonArray = new JSONArray();
					// JSONObject object = new JSONObject();
					// try {
					// // int i_gp_id = Integer.parseInt(gp_id);
					// // int i_data = Integer.parseInt(data);
					// object.put("gp_id", gp_id);
					// object.put("number", data);
					// jsonArray.put(object);
					// } catch (JSONException e) {
					// e.printStackTrace();
					// }
					map.put("user_id", userId);
					map.put("gp_id", gp_id);
					map.put("portion", data);
					map.put("type", 2 + "");// 酷币支付
					RequestTask.getInstance().doCommitGoods(this, map,
							new onCommitRequestListener());
				}

			} else {
				openActivity(LoginActivity.class);
			}

			break;
		default:
			break;
		}
	}

	// 提交请求
	private class onCommitRequestListener extends
			OnRequestListenerAdapter<Object> {
		private String order_no;
		private String amount;

		@Override
		public void onDone(XDroidRequest<?> request, String response,
				DataType dataType) {
			// TODO Auto-generated method stub
			super.onDone(request, response, dataType);
			JsonData jsonData = JsonData.create(response);

			String code = jsonData.optString("code");
			// 剩余份数不足
			if (code.equals("0")) {
				ToastUtils.show(context, jsonData.optString("message"));
			}
			// 去购物车结算
			if (code.equals("1")) {
				Intent intent = new Intent(NowJoinActivity.this,
						HomeActivity.class);
				intent.putExtra("jump_index", 3);
				startActivity(intent);
				ToastUtils.show(context, jsonData.optString("message"));
			}
			// 支付宝购买成功
			if (code.equals("2")) {
				ToastUtils.show(context, jsonData.optString("message"));
				try {
					JSONObject obj = new JSONObject(response);
					order_no = obj.getString("order_no");
					amount = obj.getString("amount");
					if (isInstalled(context)) {
						pay(amount, order_no);
					} else {
						Toast.makeText(context, "请先安装支付宝", 0).show();
					}
				} catch (JSONException e) {
					e.printStackTrace();
				}
			}
			// 酷币不足
			if (code.equals("3")) {
				ToastUtils.show(context, jsonData.optString("message"));
			}
			// 酷宝支付成功
			if (code.equals("4")) {
				ToastUtils.show(context, jsonData.optString("message"));
				Intent intent = new Intent(NowJoinActivity.this,
						PayFinishActivity.class);
				startActivity(intent);
			}
		}
	}

	private static boolean isMatch(String regex, String orginal) {
		if (orginal == null || orginal.trim().equals("")) {
			return false;
		}
		Pattern pattern = Pattern.compile(regex);
		Matcher isNum = pattern.matcher(orginal);
		return isNum.matches();
	}

	public static boolean isPositiveInteger(String orginal) {
		return isMatch("^\\+{0,1}[1-9]\\d*", orginal);
	}

	@SuppressLint("DefaultLocale")
	@SuppressWarnings("deprecation")
	private void initView() {
		flag = getTextFromBundle("flag");
		if (flag.equals("手机页面跳转") || flag.equals("详情界面跳转")
				|| flag.equals("电脑页面跳转") || flag.equals("相机页面跳转")
				|| flag.equals("其他页面跳转") || flag.equals("图文界面跳转")
				|| flag.equals("搜索页面跳转") || flag.equals("参与详情页面")) {
			title = getTextFromBundle("title");
			goodsName = getTextFromBundle("goodsName");
			allNeed = getTextFromBundle("allNeed");
			joinCount = getTextFromBundle("joinCount");
			result = getDoubleFromBundle("progress");
			gp_id = getTextFromBundle("gp_id");
			description = getTextFromBundle("description");
			int joinInt = Integer.parseInt(joinCount);
			int allInt = Integer.parseInt(allNeed);
			residue = allInt - joinInt;
			tv_goods_title_join.setText("第" + title + "期");
			tv_goods_detail_data.setText(goodsName);
			tv_goods_allPeople.setText("总需人数：" + allNeed);

			tv_goods_introduction.setText(description);
			progressBarPeople.setProgress((int) result);

			float a = Integer.parseInt(allNeed);
			double one = (1.0 / a) * 100;
			String add = String.format("%.2f", one);
			tv_Prompt.setText("友情提示：每多购买一份商品将会提升" + add + "" + "%" + "的中奖概率");

		}
		tv_buy_num.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				dialog = new Dialog(context, R.style.MyDialogStyleBottom);
				View view = View.inflate(context,
						R.layout.dialog_shopping_carts, null);
				cont = (EditText) view.findViewById(R.id.edit_dialog_count);
				cont.setInputType(InputType.TYPE_TEXT_VARIATION_PASSWORD);
				Button reduceButton = (Button) view
						.findViewById(R.id.btn_dialog_reduction);
				Button addButton = (Button) view
						.findViewById(R.id.btn_dialog_add);
				cont.setText(tv_buy_num.getText().toString().trim());
				cont.setSelection(tv_buy_num.getText().toString().trim()
						.length());
				LinearLayout cancle = (LinearLayout) view
						.findViewById(R.id.ll_cancle);
				LinearLayout ok = (LinearLayout) view.findViewById(R.id.ll_ok);
				ok.setOnClickListener(new OnClickListener() {

					@Override
					public void onClick(View v) {
						// if
						// (TextUtils.isEmpty(cont.getText().toString().trim()))
						if ((!TextUtils.isEmpty(cont.getText().toString()
								.trim()))
								&& isPositiveInteger(cont.getText().toString()
										.trim())) {
							int contInt = Integer.parseInt(cont.getText()
									.toString().trim());
							if (contInt <= residue) {
								tv_buy_num.setText(cont.getText().toString()
										.trim());
							}else{
								tv_buy_num.setText(residue+"");
							}
							dialog.dismiss();

						} else {
							Toast.makeText(NowJoinActivity.this, "非法输入", 0)
									.show();
						}

					}
				});
				cancle.setOnClickListener(new OnClickListener() {

					@Override
					public void onClick(View v) {
						dialog.dismiss();
					}
				});
				reduceButton.setOnClickListener(new OnClickListener() {

					@Override
					public void onClick(View v) {
						int oldQuantity = 0;
						oldQuantity = Integer.parseInt(cont.getText()
								.toString().trim());

						if (oldQuantity <= 1) {
							ToastUtils.show(context, "购买数量不能小于1");
							return;
						}
						dialogNum = oldQuantity - 1;
						cont.setText(dialogNum + "");
						cont.setSelection((dialogNum + "").length());
					}
				});
				addButton.setOnClickListener(new OnClickListener() {

					@Override
					public void onClick(View v) {
						int oldnum = 0;
						oldnum = Integer.parseInt(cont.getText().toString()
								.trim());

						dialogNum = oldnum + 1;
						cont.setText(dialogNum + "");
						cont.setSelection((dialogNum + "").length());
					}
				});
				dialog.setContentView(view);
				dialog.show();
				// cont获得焦点弹出键盘
				Timer timer = new Timer();
				timer.schedule(new TimerTask() {
					@Override
					public void run() {
						InputMethodManager m = (InputMethodManager) cont
								.getContext().getSystemService(
										Context.INPUT_METHOD_SERVICE);
						m.toggleSoftInput(0, InputMethodManager.HIDE_NOT_ALWAYS);
					}
				}, 300);

				cont.setInputType(EditorInfo.TYPE_CLASS_PHONE);

			}
		});

	}

	public static boolean isNumeric(String str) {
		for (int i = str.length(); --i >= 0;) {
			if (!Character.isDigit(str.charAt(i))) {
				return false;
			}
		}
		return true;
	}

	/**
	 * 初始化下拉刷新
	 */
	private void initPtr() {
		/* 创建自定义刷新头部view */
		ptrHeader = new PtrHeader(this);
		/* 设置刷新头部view */
		ptr_view.setHeaderView(ptrHeader);
		/* 设置回调 */
		ptr_view.addPtrUIHandler(ptrHeader);
		/* 横向拉动时，禁止下拉 */
		ptr_view.disableWhenHorizontalMove(true);
		// 设置监听
		ptr_view.setPtrHandler(new PtrHandler() {

			@Override
			public void onRefreshBegin(PtrFrameLayout frame) {
				frame.postDelayed(new Runnable() {

					@Override
					public void run() {

						getData();

					}

				}, 500);
			}

			@Override
			public boolean checkCanDoRefresh(PtrFrameLayout frame,
					View content, View header) {
				// TODO Auto-generated method stub
				return PtrDefaultHandler.checkContentCanBePulledDown(frame,
						content, header);
			}
		});
		/* 延时100hao秒,自动刷新 */
		ptr_view.postDelayed(new Runnable() {

			@Override
			public void run() {
				ptr_view.autoRefresh();
			}
		}, 100);
	}

	/**
	 * 初始化轮播图
	 */
	private void initSliderBanner() {
		RelativeLayout.LayoutParams lyp = new RelativeLayout.LayoutParams(
				ScreenUtils.getScreenWidth(context),
				(int) (ScreenUtils.getScreenWidth(context) * 1f / 16 * 9.6f));
		sliderBanner.setLayoutParams(lyp);
		mainSliderBanner = new MainSliderBannerOne(sliderBanner);
	}

	// 此方法，判断第一次页面加载 支付方式，默认 支付宝
	public void initType() {
		type = 0;
		img_kubi.setVisibility(View.GONE);
		img_pay.setVisibility(View.VISIBLE);
	}

	// 清空选中模式
	public void clearType() {
		type = 0;
		img_kubi.setVisibility(View.GONE);
		img_pay.setVisibility(View.GONE);
	}

	// 支付宝支付功能

	// 复制到支付的页面，购物车点击提交的页面

	// 商户PID
	public static final String PARTNER = "2088611733777860";
	// 商户收款账号
	public static final String SELLER = "18655386599@163.com";
	// 商户私钥，pkcs8格式

	public static final String RSA_PRIVATE = "MIICdwIBADANBgkqhkiG9w0BAQEFAASCAmEwggJdAgEAAoGBAORKbnGihXbb6eneu7mw7O82T46dgpwUqJtMZeppp7lQJK93UALMokKKLO7VeeC+C5UpHtd8pNMzM+LCw8Bs7rCH+JaQLGsTgY/l +TZEPv6eZoifhcbeyA5VZhF4pblYTAJfd8GgKkFiqSC6QeAAwA5gYQLXuwQZjDmEy6e7r6mBAgMBAAECgYA/dr2rU3384/fsLyJK5feILLYDNKB5mXih66QtfX/GEZSRPv78OD0neFgzcR83rj10EwFi8GC14fcbo/9dQCs +W57SYJVtrZLjCv7BQEYW66LVhSHyJ66IQnkQdh3ejqew4N3CwQ2CgJDsFJRNPg +ceP91Tev9+b7t06xqTrRQbQJBAPqQnoXDJsyLGPd0vBe2tENx7RmcWRJ2TKPz4DCXeFBGjGNc8tl9yklgybrXE61sqKRc1QGPLtxtNpXA9B7iKOcCQQDpPh/QaQnIIMrY9zdm5YSS06e0vPd2rmlWtmX1BajDs1oSNmGy3ysfXF4rvll3IWU/hej +foMVrjpbhzlklsVXAkEAuLeIxd+6aKxauYLLb0f32IjSXEEQwTWJBo0xR2FDBxsbP900AvZi/Hln/l+0V/N018bAGSgvSb0RspDO5z2fHQJBAN6u61zlC +vAMyqWTJS2yK4N2W3bhEARII0jM5CNSKUfVP1SYlCOdPNKErac03nDrpDJXrurOae3YgwEvKzmrZ0CQHPCe0V0mhIbgRceSCvbo8xXr3Up707gQ3wiSByufYTIKyDCWxec6FRUzx4jk82cVWoT+jTK26mqJprIcrsQMiw=";

	// 支付宝公钥
	public static final String RSA_PUBLIC = "MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQCnxj/9qwVfgoUh/y2W89L6BkRAFljhNhgPdyPuBV64bfQNN1PjbCzkIM6qRdKBoLPXmKKMiFYnkd6rAoprih3/PrQEB/VsW8OoM8fxn67UDYuyBTqA23MML9q1+ilIZwBC2AQ2UBVOrFXfFl75p6/B5KsiNG9zpgmLCUYuLkxpLQIDAQAB";

	private static final int SDK_PAY_FLAG = 1;

	private static final int SDK_CHECK_FLAG = 2;

	private Handler mHandler = new Handler() {
		public void handleMessage(Message msg) {
			switch (msg.what) {
			case SDK_PAY_FLAG: {
				PayResult payResult = new PayResult((String) msg.obj);

				// 支付宝返回此次支付结果及加签，建议对支付宝签名信息拿签约时支付宝提供的公钥做验签
				String resultInfo = payResult.getResult();

				String resultStatus = payResult.getResultStatus();

				// 判断resultStatus 为“9000”则代表支付成功，具体状态码代表含义可参考接口文档
				if (TextUtils.equals(resultStatus, "9000")) {
					Toast.makeText(NowJoinActivity.this, "支付成功",
							Toast.LENGTH_SHORT).show();
					Intent intent = new Intent(NowJoinActivity.this,
							PayFinishActivity.class);
					startActivity(intent);

				} else {
					// 判断resultStatus 为非“9000”则代表可能支付失败
					// “8000”代表支付结果因为支付渠道原因或者系统原因还在等待支付结果确认，最终交易是否成功以服务端异步通知为准（小概率状态）
					if (TextUtils.equals(resultStatus, "8000")) {
						Toast.makeText(NowJoinActivity.this, "支付结果确认中",
								Toast.LENGTH_SHORT).show();

					} else {
						// 其他值就可以判断为支付失败，包括用户主动取消支付，或者系统返回的错误
						Toast.makeText(NowJoinActivity.this, "支付失败",
								Toast.LENGTH_SHORT).show();

					}
				}
				break;
			}
			case SDK_CHECK_FLAG: {
				Toast.makeText(NowJoinActivity.this, "检查结果为：" + msg.obj,
						Toast.LENGTH_SHORT).show();
				break;
			}
			default:
				break;
			}
		};
	};
	private int old_amount;

	/**
	 * call alipay sdk pay. 调用SDK支付
	 * 
	 */
	public void pay(String price, String order_id) {
		// 订单
		String orderInfo = getOrderInfo("酷喜乐购", "酷喜商品", price, order_id);

		// 对订单做RSA 签名
		String sign = sign(orderInfo);
		try {
			// 仅需对sign 做URL编码
			sign = URLEncoder.encode(sign, "UTF-8");
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		}

		// 完整的符合支付宝参数规范的订单信息
		final String payInfo = orderInfo + "&sign=\"" + sign + "\"&"
				+ getSignType();

		Runnable payRunnable = new Runnable() {

			@Override
			public void run() {
				// 构造PayTask 对象
				PayTask alipay = new PayTask(NowJoinActivity.this);
				// 调用支付接口，获取支付结果
				String result = alipay.pay(payInfo);
				Message msg = new Message();
				msg.what = SDK_PAY_FLAG;
				msg.obj = result;
				mHandler.sendMessage(msg);
			}
		};

		// 必须异步调用
		Thread payThread = new Thread(payRunnable);
		payThread.start();
	}

	/**
	 * check whether the device has authentication alipay account.
	 * 查询终端设备是否存在支付宝认证账户
	 * 
	 */
	public void check(View v) {
		Runnable checkRunnable = new Runnable() {

			@Override
			public void run() {
				// 构造PayTask 对象
				PayTask payTask = new PayTask(NowJoinActivity.this);
				// 调用查询接口，获取查询结果
				boolean isExist = payTask.checkAccountIfExist();
				Message msg = new Message();
				msg.what = SDK_CHECK_FLAG;
				msg.obj = isExist;
				mHandler.sendMessage(msg);
			}
		};

		Thread checkThread = new Thread(checkRunnable);
		checkThread.start();

	}

	/**
	 * get the sdk version. 获取SDK版本号
	 * 
	 */
	public void getSDKVersion() {
		PayTask payTask = new PayTask(this);
		String version = payTask.getVersion();
		Toast.makeText(this, version, Toast.LENGTH_SHORT).show();
	}

	/**
	 * create the order info. 创建订单信息
	 * 
	 */
	public String getOrderInfo(String subject, String body, String price,
			String order_id) {
		// 签约合作者身份ID
		String orderInfo = "partner=" + "\"" + PARTNER + "\"";

		// 签约卖家支付宝账号
		orderInfo += "&seller_id=" + "\"" + SELLER + "\"";

		// 商户网站唯一订单号
		orderInfo += "&out_trade_no=" + "\"" + order_id + "\"";

		// 商品名称
		orderInfo += "&subject=" + "\"" + subject + "\"";

		// 商品详情
		orderInfo += "&body=" + "\"" + body + "\"";

		// 商品金额
		orderInfo += "&total_fee=" + "\"" + price + "\"";

		// 服务器异步通知页面路径
		orderInfo += "&notify_url=" + "\""
				+ "http://www.aikuxi.com/api/alipay/callback" + "\"";// homer发过来

		// 服务接口名称， 固定值
		orderInfo += "&service=\"mobile.securitypay.pay\"";

		// 支付类型， 固定值
		orderInfo += "&payment_type=\"1\"";

		// 参数编码， 固定值
		orderInfo += "&_input_charset=\"utf-8\"";

		// 设置未付款交易的超时时间
		// 默认30分钟，一旦超时，该笔交易就会自动被关闭。
		// 取值范围：1m～15d。
		// m-分钟，h-小时，d-天，1c-当天（无论交易何时创建，都在0点关闭）。
		// 该参数数值不接受小数点，如1.5h，可转换为90m。
		orderInfo += "&it_b_pay=\"30m\"";

		// extern_token为经过快登授权获取到的alipay_open_id,带上此参数用户将使用授权的账户进行支付
		// orderInfo += "&extern_token=" + "\"" + extern_token + "\"";

		// 支付宝处理完请求后，当前页面跳转到商户指定页面的路径，可空
		orderInfo += "&return_url=\"m.alipay.com\"";

		// 调用银行卡支付，需配置此参数，参与签名， 固定值 （需要签约《无线银行卡快捷支付》才能使用）
		// orderInfo += "&paymethod=\"expressGateway\"";

		return orderInfo;
	}

	/**
	 * get the out_trade_no for an order. 生成商户订单号，该值在商户端应保持唯一（可自定义格式规范）
	 * 
	 */
	public String getOutTradeNo() {
		SimpleDateFormat format = new SimpleDateFormat("MMddHHmmss",
				Locale.getDefault());
		Date date = new Date();
		String key = format.format(date);

		Random r = new Random();
		key = key + r.nextInt();
		key = key.substring(0, 15);
		return key;
	}

	/**
	 * sign the order info. 对订单信息进行签名
	 * 
	 * @param content
	 *            待签名订单信息
	 */
	public String sign(String content) {
		return SignUtils.sign(content, RSA_PRIVATE);
	}

	/**
	 * get the sign type we use. 获取签名方式
	 * 
	 */
	public String getSignType() {
		return "sign_type=\"RSA\"";
	}

	// ////////////////////////////////////////////////////////////////////////////////////////////

}
